<template>
  <el-dialog class='addApp-modal' v-model="visible" :title="data.title" @close="close" :width="650">
    <el-form :label-width="90" :model="data.form" ref="formRef" :rules="data.formRules">
      <el-form-item label="菜单类型" prop="clientId">
        <el-radio-group v-model="data.form.type" :disabled='!!defaultData' @change="menuTypeChange">
          <el-radio v-for="item in data.form.typeList" :label="item.value" :key="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="打开方式" prop="openMode" v-if="data.form.type != menuTypes.BUTTON">
        <el-radio-group v-model="data.form.openMode">
          <el-radio :label="0">内链接</el-radio>
          <el-radio :label="1">外链接</el-radio>
          <el-radio :label="2">嵌入链接</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上级菜单" prop="parentId" v-if="data.form.type != menuTypes.DIR">
        <el-tree-select v-model="data.form.parentId" :data="menuListOpts" check-strictly label="menuName"
          class="w-full"></el-tree-select>
      </el-form-item>
      <el-form-item :label="data.form.type == menuTypes.BUTTON ? '按钮名称' : '菜单名称'" prop="menuName">
        <el-input v-model="data.form.menuName" />
      </el-form-item>
      <el-form-item label="菜单别名" prop="menuUrl" v-if="data.form.type != menuTypes.BUTTON">
        <el-input v-model="data.form.menuUrl" />
      </el-form-item>
      <!-- 这里使用了v-if来做校验规则prop的判断，没有用v-bind绑定prop因为有bug -->
      <el-form-item label="授权标识" v-if='data.form.type != menuTypes.BUTTON'>
        <el-input v-model="data.form.btnPermission" />
      </el-form-item>
      <el-form-item label="授权标识" prop="btnPermission" v-else>
        <el-input v-model="data.form.btnPermission" />
      </el-form-item>
      <el-form-item :label="data.form.type == menuTypes.BUTTON ? '按钮排序' : '菜单排序'" prop="sort">
        <el-input-number v-model="data.form.sort" controls-position="right" class='w-full' />
      </el-form-item>
      <el-form-item label="菜单url" prop="path" v-if="data.form.type != menuTypes.BUTTON">
        <el-input v-model="data.form.path" />
      </el-form-item>
      <el-form-item label="组件url" prop="componentPath" v-if="data.form.type != menuTypes.BUTTON">
        <el-input v-model="data.form.componentPath" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="data.form.remark" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="data.submitEvent" :loading="state.loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, toRefs, watch, ref, computed, nextTick } from 'vue'
import { addMenuReq, updateMenuReq } from '/@/api/menu';
import { useMessage } from '/@/hooks/web/useMessage'
import { MENU_TYPE_LIST, menuTypes } from './enum'
import { noNegative } from '/@/utils/formRules'
import { recursionFilter } from '/@/utils/treeData'

const { createMessage } = useMessage();

const state = reactive({
  loading: false
})

const props = defineProps({
  data: {
    type: Object || undefined,
    default: () => undefined
  },
  visible: {
    type: Boolean,
    default: false,
  },
  menuList: {
    type: Array || undefined,
    default: () => []
  }
});

const emit = defineEmits(['success', 'update:visible'])

const data = reactive({
  title: '新建菜单',
  updateMode: false,
  form: {
    id: '',
    menuName: '',
    menuUrl: '',
    sort: 0,
    path: '',
    componentPath: '',
    remark: '',
    type: MENU_TYPE_LIST[0].value,
    typeList: MENU_TYPE_LIST,
    parentId: '',
    menuList: [],
    btnPermission: '',
    showList: [{ label: '是', value: 1 }, { label: '否', value: 0 }],
    openMode: 0,
  },
  formRules: {
    menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    menuUrl: [{ required: true, message: '请输入菜单别名', trigger: 'blur' }],
    sort: [
      { required: true, message: '请输入菜单排序', trigger: 'blur', type: 'number' },
      { validator: noNegative, trigger: 'change' }
    ],
    // componentPath: [{ required: true, message: '请输入组件url', trigger: 'blur' }],
    // path: [{ required: true, message: '请输入菜单url', trigger: 'blur' }],
    type: [{ required: true, message: '请选择菜单类型', trigger: 'blur', type: 'number' }],
    // parentId: [{ required: true, message: '请选择菜单上级', trigger: 'blur', type: 'number' }],
    btnPermission: [{ required: true, message: '请输入按钮授权标识', trigger: 'blur' }],
  },
  treeData: [],
  submitEvent: () => null as any,
});

const { data: defaultData, menuList, visible } = toRefs(props);
const menuListOpts = computed(() => {
  let ret = recursionFilter(menuList.value, (e) => e.id != defaultData?.value?.id, { label: 'menuName', value: 'id' })
  console.log('ret', ret, 'data.form.parentId', data.form.parentId)
  return ret;
})

const createAction = () => {
  formRef.value.validate(async v => {
    if(v) {
      const { menuName, menuUrl, sort, path, type, parentId, componentPath, remark, btnPermission, openMode } = data.form;
      let p = { menuName, menuUrl, sort, path, type, parentId, componentPath, remark, btnPermission, openMode }
      state.loading = true;
      const { code, msg } = await addMenuReq(p);
      state.loading = false;
      createMessage({
        message: msg,
      });
      if (code == 200) {
        emit('update:visible', false);
        emit('success')
      }
    }
  })
};
const updateAction = () => {
  formRef.value.validate(async v => {
    if(v) {
      const { menuName, menuUrl, sort, path, type, parentId, componentPath, remark, btnPermission, id, openMode } = data.form;
      let p = { menuName, menuUrl, sort, path, type, parentId, id, componentPath, remark, btnPermission, openMode }
      state.loading = true;
      const { code, msg } = await updateMenuReq(p);
      state.loading = false;
      if (code == 200) {
        createMessage({
          message: msg,
        });
        emit('update:visible', false);
        emit('success')
      }
    }
  })
};
data.submitEvent = createAction;

const formRef = ref();
watch(visible, (nv: any) => {
  if (nv) {
    data.updateMode = props.data?.id ? true : false;
    data.title = data.updateMode ? '编辑菜单' : '新建菜单';
    data.submitEvent = data.updateMode ? updateAction : createAction;
    if (data.updateMode) {
      nextTick(() => {
        data.form.id = defaultData?.value?.id || undefined;
        data.form.menuName = defaultData?.value?.menuName;
        data.form.menuUrl = defaultData?.value?.menuUrl;
        data.form.path = defaultData?.value?.path;
        data.form.componentPath = defaultData?.value?.componentPath;
        data.form.sort = defaultData?.value?.sort;
        data.form.type = defaultData?.value?.type;
        data.form.remark = defaultData?.value?.remark;
        data.form.parentId = defaultData?.value?.parentId;
        data.form.btnPermission = defaultData?.value?.btnPermission;
        data.form.openMode = +defaultData?.value?.openMode;
      })
    }
  }
})

const menuTypeChange = () => {
  formRef.value.resetFields()
  data.form.parentId = ''
}

const close = () => {
  formRef.value.resetFields();
  emit('update:visible', false)
}
</script>
